如何连接多个字符串(C# 指南) 您所在的位置:网站首页 char *字符串拼接 如何连接多个字符串(C# 指南)

如何连接多个字符串(C# 指南)

2023-08-28 13:46| 来源: 网络整理| 查看: 265

如何连接多个字符串(C# 指南) 项目 05/10/2023

串联是将一个字符串追加到另一字符串末尾的过程。 可使用 + 运算符连接字符串。 对于字符串文本和字符串常量,会在编译时进行串联,运行时不串联。 对于字符串变量,仅在运行时串联。

注意

本文中的 C# 示例运行在 Try.NET 内联代码运行程序和演练环境中。 选择“运行”按钮以在交互窗口中运行示例。 执行代码后,可通过再次选择“运行”来修改它并运行已修改的代码。 已修改的代码要么在交互窗口中运行,要么编译失败时,交互窗口将显示所有 C# 编译器错误消息。

字符串文本

以下示例将长字符串字面量拆分为较短的字符串,从而提高源代码的可读性。 以下代码将较短的字符串连接起来,以创建长字符串字面量。 在编译时将这些部分连接成一个字符串。 无论涉及到多少个字符串,均不产生运行时性能开销。

// Concatenation of literals is performed at compile time, not run time. string text = "Historically, the world of data and the world of objects " + "have not been well integrated. Programmers work in C# or Visual Basic " + "and also in SQL or XQuery. On the one side are concepts such as classes, " + "objects, fields, inheritance, and .NET Framework APIs. On the other side " + "are tables, columns, rows, nodes, and separate languages for dealing with " + "them. Data types often require translation between the two worlds; there are " + "different standard functions. Because the object world has no notion of query, a " + "query can only be represented as a string without compile-time type checking or " + "IntelliSense support in the IDE. Transferring data from SQL tables or XML trees to " + "objects in memory is often tedious and error-prone."; System.Console.WriteLine(text); + 和 += 运算符

若要连接字符串变量,可使用 + 或 += 运算符、字符串内插或 String.Format、String.Concat、String.Join、StringBuilder.Append 方法。 + 运算符易于使用,有利于产生直观代码。 即使在一个语句中使用多个 + 运算符,字符串内容也仅会被复制一次。 以下代码演示使用 + 和 += 运算符串联字符串的示例:

string userName = ""; string dateString = DateTime.Today.ToShortDateString(); // Use the + and += operators for one-time concatenations. string str = "Hello " + userName + ". Today is " + dateString + "."; System.Console.WriteLine(str); str += " How are you today?"; System.Console.WriteLine(str); 字符串内插

在某些表达式中,使用字符串内插进行字符串串联更简单,如以下代码所示:

string userName = ""; string date = DateTime.Today.ToShortDateString(); // Use string interpolation to concatenate strings. string str = $"Hello {userName}. Today is {date}."; System.Console.WriteLine(str); str = $"{str} How are you today?"; System.Console.WriteLine(str);

注意

在字符串串联操作中,C# 编译器将 null 字符串视为空字符串进行处理。

从 C# 10 开始,当用于占位符的所有表达式也是常量字符串时,可以使用字符串内插来初始化常量字符串。

String.Format

另一个字符串连接方法为 String.Format。 此方法非常适合从少量组件字符串生成字符串的情况。

StringBuilder

在其他情况下,可能需要将字符串合并在循环中,此时不知道要合并的源字符串的数量,而且源字符串的实际数量可能很大。 StringBuilder 类专门用于此类方案。 以下代码使用 StringBuilder 类的 Append 方法串联字符串。

// Use StringBuilder for concatenation in tight loops. var sb = new System.Text.StringBuilder(); for (int i = 0; i < 20; i++) { sb.AppendLine(i.ToString()); } System.Console.WriteLine(sb.ToString());

有关详细信息,请阅读选择字符串串联或 StringBuilder 类的原因。

String.Concat 或 String.Join

还可使用 String.Concat 方法联接集合中的字符串。 如果源字符串应使用分隔符分隔,请使用 String.Join 方法。 以下代码使用这两种方法合并单词数组:

string[] words = { "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog." }; var unreadablePhrase = string.Concat(words); System.Console.WriteLine(unreadablePhrase); var readablePhrase = string.Join(" ", words); System.Console.WriteLine(readablePhrase); LINQ 和 Enumerable.Aggregate

最后,可以使用 LINQ 和 Enumerable.Aggregate 方法联接集合中的字符串。 此方法利用 lambda 表达式合并源字符串。 lambda 表达式用于将所有字符串添加到现有累积。 下面的示例通过在数组中的每两个单词之间添加一个空格来合并单词数组:

string[] words = { "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog." }; var phrase = words.Aggregate((partialPhrase, word) =>$"{partialPhrase} {word}"); System.Console.WriteLine(phrase);

与其他集合连接方法相比,该选项可能会导致更多的分配,因为每次迭代它都会创建一个中间字符串。 如果优化性能至关重要,请考虑使用 StringBuilder 类或 String.Concat 或 String.Join 方法来连接集合,而不是使用 Enumerable.Aggregate。

请参阅 String StringBuilder C# 编程指南 字符串


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有